import dayjs from 'dayjs';

/** 处理生成json */
// 把Array转json，key是code
FDUI.fieldsToObject = function (fields, key = 'code') {
  if (Array.isArray(fields)) {
    const objFields = {};
    fields.forEach(item => {
      objFields[item[key]] = item;
    });
    return objFields;
  }
  return fields;
};
// 把json转array
FDUI.fieldsToArray = function (fields) {
  if (Array.isArray(fields)) {
    return fields;
  }
  return Object.keys(fields).map(i => fields[i]);
};
/**
 * @param {any} field 字段
 * @param {any} config 配置项，放到__config__中
 * @param {any} params lookup参数
 * @param {any} data form参数
 * @returns
 */
function fieldToJson(field, config = {}, params = {}, data = {}, rule = {}, fields = []) {
  const defaultConfig = {
    span: 8
  };
  config = Object.assign(defaultConfig, config);
  if (!field || !field.eleType) {
    return;
  }
  const { eleType, eleDisType, code, name, isNull, __config__: fieldConfig } = field;
  let { labelWidth } = fieldConfig || {};
  if (labelWidth && !labelWidth.includes('px')) {
    labelWidth += 'px';
  }
  const tag = `ele-distype-${eleDisType}`;
  const fieldOption = {
    __config__: {
      key: code,
      label: name,
      labelWidth: labelWidth || '',
      tag,
      required: !isNull,
      ...config
    }
  };
  if (FDUI.eleType.Check == eleType) {
    fieldOption['true-label'] = 1;
    fieldOption['false-label'] = 0;
  }
  if (FDUI.eleType.Date == eleType) {
    if (field.dataFormat) {
      const dataFormat = field.dataFormat.replace('yyyy', 'YYYY').replace('dd', 'DD');
      fieldOption.format = dataFormat;
      fieldOption['picker-options'] = { format: dataFormat };
    }
  }
  if (FDUI.eleType.CodeData == eleType || FDUI.eleType.LookUp == eleType || FDUI.eleType.Service == eleType) {
    const options = [];
    // 存在值从refdata中拼接选项
    if (Object.hasOwn(data, code)) {
      if (String(data[code]) !== '') {
        const codes = String(data[code]).split(',');
        const REFNAME = `${code}NAME`;
        const refDatas = ((data.REFDATA && data.REFDATA[REFNAME]) || '').split(',');
        codes.forEach((code, index) => {
          options.push({
            code,
            name: refDatas[index] || code
          });
        });
      }
    }
    fieldOption.__extend__ = {
      options
    };
  } else {
    fieldOption.__extend__ = {
      options: []
    };
  }
  fieldOption.__server__ = field;
  fieldOption.__lookup__ = params;
  fieldOption.__data__ = data;
  fieldOption.__rule__ = rule;
  fieldOption.__fields__ = JSON.parse(JSON.stringify(fields));
  return fieldOption;
}
FDUI.fieldToJson = fieldToJson;
/**
 * 公共组件转成json
 *
 * @param {any} field 字段
 * @param {any} config 配置项，放到__config__中
 * @param {any} params lookup参数
 * @param {any} data form参数
 * @returns
 */
function componentToJson(field, config = {}, params = {}, data = {}, rule = {}, fields = []) {
  const defaultConfig = {
    span: 8
  };
  config = Object.assign(defaultConfig, config);
  if (!field || !field.isCom) {
    return;
  }
  const { eleType, type, ComName, isNull } = field;
  const tag = `ele-distype-${type}`;
  const fieldOption = {
    __config__: {
      key: '',
      label: '',
      labelWidth: '0px',
      tag,
      required: !isNull,
      ...config
    }
  };
  // __config__属性放到根部
  Object.keys(field.__config__ || {}).forEach(key => {
    fieldOption[key] = field.__config__[key];
  });
  fieldOption.__slot__ = field.__slot__ || {};
  fieldOption.__server__ = field;
  fieldOption.__lookup__ = params;
  fieldOption.__data__ = data;
  fieldOption.__rule__ = rule;
  fieldOption.__fields__ = JSON.parse(JSON.stringify(fields));
  return fieldOption;
}
/**
 * 插槽转成json
 *
 * @param {any} field 字段
 * @param {any} config 配置项，放到__config__中
 * @param {any} params lookup参数
 * @param {any} data form参数
 * @returns
 */
function slotToJson(field, config = {}, params = {}, data = {}, rule = {}, fields = []) {
  const defaultConfig = {
    span: 8
  };
  config = Object.assign(defaultConfig, config);
  if (!field || !field.isSlot) {
    return;
  }
  const { type, __config__: fieldConfig } = field;
  let { key, showLabel, labelName, slotName, labelWidth, isNull } = fieldConfig;
  if (labelWidth && !labelWidth.includes('px')) {
    labelWidth += 'px';
  }
  const tag = `ele-distype-${type}`;
  const fieldOption = {
    __config__: {
      key: key || '',
      label: showLabel ? labelName : '',
      labelWidth: showLabel ? labelWidth || '' : '0px',
      tag,
      required: !isNull,
      slot: true,
      slotName,
      ...config
    }
  };
  // __config__属性放到根部
  Object.keys(field.__config__ || {}).forEach(key => {
    fieldOption[key] = field.__config__[key];
  });
  fieldOption.__slot__ = field.__slot__ || {};
  fieldOption.__server__ = field;
  fieldOption.__lookup__ = params;
  fieldOption.__data__ = data;
  fieldOption.__rule__ = rule;
  fieldOption.__fields__ = JSON.parse(JSON.stringify(fields));
  return fieldOption;
}
/**
 * 创建组成custom-form的json
 *
 * @param {any} fields 所有字段
 * @param {any} form 给form初始值
 * @param {any} params lookup参数
 * @returns
 */
FDUI.createForm = function (fields, form, params = {}, data, rule, isComplex = false, allFields) {
  const defaultConfig = {
    colCount: 2
  };
  const prettyFields = [];
  // const cFields = isComplex ? allFields : fields
  fields
    .filter(field => {
      // 全部字段给form属性
      if (field.code) {
        form[field.code] = '';
      }
      return field.accessRight !== 0;
    })
    .sort((pre, next) => {
      return pre.orderId >= next.orderId ? 1 : -1;
    })
    .forEach(field => {
      let span = 24 / defaultConfig;
      if (field.colSpan) {
        span = field.colSpan;
        // 兼容历史数据，后续可以删除
        if (span === 1) {
          span = 12;
        } else if (span === 2) {
          span = 24;
        }
      }
      if (field.isCom) {
        // 自定义公共组件
        const fieldOption = componentToJson(
          field,
          {
            span
          },
          params,
          data,
          rule,
          isComplex ? allFields : fields
        );
        if (field.code) {
          form[field.code] = '';
        }
        prettyFields.push(fieldOption);
      } else if (field.isSlot) {
        // 插槽
        const fieldOption = slotToJson(
          field,
          {
            span
          },
          params,
          data,
          rule,
          isComplex ? allFields : fields
        );
        if (field.code) {
          form[field.code] = '';
        }
        prettyFields.push(fieldOption);
      } else {
        const fieldOption = fieldToJson(
          field,
          {
            span
          },
          params,
          data,
          rule,
          isComplex ? allFields : fields
        );
        // 复选框默认0其他默认空字符串
        if (field.eleType === '3') {
          form[field.code] = 0;
        } else {
          form[field.code] = '';
        }
        prettyFields.push(fieldOption);
      }
    });
  return [prettyFields];
};

FDUI.createTableFilter = function (layout, fields, filter) {
  // 字段转对象，方便取值
  fields = JSON.parse(JSON.stringify(FDUI.fieldsToObject(fields)));
  // 根据childFields对页面进行布局
  const prettyFields = [];
  layout.forEach(item => {
    const childFields = [];
    // 普通查询
    const key = item.columnCode;
    const firstKey = item.columnCode.split(',')[0];
    const defaultValue = item.defaultValue;
    let field = fields[key];
    if (!fields[key]) {
      field = fields[firstKey];
      field.code = key;
    }
    field.isMultivalued = 0;
    // 多值允许多选
    if (item.filterType == '6' || item.filterType == '7') {
      field.isMultivalued = 1;
      field.valuesCount = 0;
    }
    field.isNull = item.required == 1 ? 0 : 1; // 筛选条件必填
    field.rowSpan = 1; // 筛选条件只有一行
    // 自定义显示类型
    if (item.disType) {
      field.eleDisType = item.disType;
    }
    // 复选框筛选条件改成下拉
    if (field.eleType === '3') {
      field.eleDisType = '60';
      field.codeTypeId = 'YES_NO';
    }
    // 筛选条件使用pageId
    const params = {
      funcCode: window.$CD.pageId,
      formId: window.$CD.pageId
    };
    const fieldOption = fieldToJson(
      field,
      {
        span: 8
      },
      params
    );
    // 筛选条件不置灰
    fieldOption.disabled = false;
    // 如果有defaultValueName需要回填到option中
    if (item.defaultValue && item.defaultValueName) {
      fieldOption.__extend__ = {
        options: [
          {
            code: item.defaultValue,
            name: item.defaultValueName
          }
        ]
      };
    }
    if (item.aliasName) {
      fieldOption.__config__.label = item.aliasName;
    }
    // 范围
    if (item.filterType == '5') {
      fieldOption.__range__ = [0, 1].map(index => {
        const params = {
          funcCode: window.$CD.pageId,
          formId: window.$CD.pageId
        };
        const fieldOption = fieldToJson(
          field,
          {
            span: 8
          },
          params
        );
        fieldOption.disabled = false;
        fieldOption.__config__.key = `${field.code}_${index}`;
        filter[`${field.code}_${index}`] = defaultValue;
        if (defaultValue === '@@C.datetime') {
          if (index === 0) {
            filter[`${field.code}_${index}`] = dayjs().format('YYYY-MM-DD 00:00:00');
          } else {
            filter[`${field.code}_${index}`] = dayjs().format('YYYY-MM-DD HH:mm:ss');
          }
        }
        return fieldOption;
      });
    }
    if (fieldOption) {
      childFields.push(fieldOption);
      // 筛选条件参数初始化
      filter[field.code] = defaultValue;
      if (item.filterType == '5' && defaultValue) {
        filter[field.code] = [defaultValue, defaultValue];
        if (defaultValue === '@@C.datetime') {
          filter[field.code] = [dayjs().format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD HH:mm:ss')];
        }
      }
    }
    if (childFields && childFields.length) {
      prettyFields.push(childFields);
    }
  });
  return prettyFields;
};

FDUI.getLableWidth = function (fields) {
  fields = FDUI.fieldsToArray(fields);
  const sortedFields = fields.sort((pre, next) => (pre.name.length > next.name.length ? -1 : 1));
  if (sortedFields && sortedFields.length) {
    return `${sortedFields[0].name.length * 16 + 16}px`;
  }
  return '125px';
};

function getLables(fields) {
  const labels = [];
  fields.forEach(field => {
    if (Array.isArray(field)) {
      field.forEach(i => {
        labels.push(i.__config__.label);
      });
    } else {
      labels.push(field.__config__.label);
    }
  });
  return labels;
}

/**
 * 获取准确宽度 通过创建dom获取真实的宽度
 *
 * @param fields Array：可能存在两级
 * @returns 最大宽度
 */
FDUI.getExactLableWidth = function (fields) {
  const labels = getLables(fields);
  const style = document.createElement('p').style;
  const fontSize = 16; // 设置字体大小（以像素为单位）
  style.fontSize = `${fontSize}px`;
  style.fontFamily = 'Arial'; // 设置字体
  style.display = 'none'; // 隐藏元素以避免影响页面布局
  const divContainer = document.createElement('div');
  divContainer.style =
    'font-size:16px;font-family:Arial;padding:0 6px;display:inline-block;position:fixed;top:-10000px;right:-10000px;z-index:-1;';
  labels.forEach(label => {
    const labelElement = document.createElement('p');
    labelElement.innerText = label;
    divContainer.append(labelElement);
  });
  document.body.appendChild(divContainer); // 创建新的div元素
  return `${Math.ceil(divContainer.getBoundingClientRect().width + 8)}px`;
};

FDUI.createGrid = function () {};

FDUI.createGroups = function () {};

FDUI.createTabs = function () {};

export default {
  createForm: FDUI.createForm,
  createGrid: FDUI.createGrid,
  createGroups: FDUI.createGroups,
  createTabs: FDUI.createTabs
};
